package com.seven.commons;

import com.google.common.base.Charsets;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import org.junit.Test;

import java.util.*;

/**
 * @工程名:common-utils
 * @作者: sevenDay
 * @时间: 2019/5/10 09:12
 * @描述:
 */
public class GuavaBloomFilterFilter {

    @Test
    public void testBloom() {
        final int count = 500000;
        List<String> stringList = new ArrayList<>(count);
        Set<String> stringSet = new HashSet<>();
        //创建布隆过滤器 初始化过滤器数据
        BloomFilter<String> bloomString = BloomFilter.create(Funnels.stringFunnel(Charsets.UTF_8), count, 0.001);
        for (int i = 0; i < count; i++) {
            String id = "" + i;
            stringList.add(id);
            stringSet.add(id);
            bloomString.put(id);
        }
        int wrong = 0;
        int right = 0;
        for (int i = 0; i < count + 50000; i++) {
            String checkString = "" + i;
            //布隆过滤器 进过hash算法和byte数组 校验是否存在于集合中
            if (bloomString.mightContain(checkString)) {
                //校验是否误判
                //校验是否误判
                if (stringSet.contains(checkString)) {
                    right++;
                } else {
                    wrong++;
                }
            }

        }
        System.out.println("50万测试数据-->共抵挡: " + (count - wrong - right) + "次非法入侵" + "    误判" + wrong);
    }
}
